import cv2
import numpy as np

# 读取图像
image = cv2.imread('image.jpg', cv2.IMREAD_GRAYSCALE)

# 应用Sobel算子
sobel_x = cv2.Sobel(image, cv2.CV_64F, 1, 0, ksize=3)  # x方向梯度
sobel_y = cv2.Sobel(image, cv2.CV_64F, 0, 1, ksize=3)  # y方向梯度

# 计算梯度幅值
sobel_magnitude = np.sqrt(sobel_x**2 + sobel_y**2)
sobel_magnitude = np.uint8(sobel_magnitude)

# 显示结果
cv2.imshow('Original Image', image)
cv2.imshow('Sobel Edge Detection', sobel_magnitude)
cv2.waitKey(0)
cv2.destroyAllWindows()